<script setup lang="ts">
import { reactive, ref, toRefs, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import {
  getClassroomApi,
  addClassroomApi,
  delClassroomApi,
  getClassroomByIdApi,
  editClassroomApi,
} from "@/http/Api/teachers/classroomManageApi";

const title = ref("新增教室");
// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
  getInitData();
};

// 搜索
// const searchFormRef = ref<FormInstance>();
// const searchCondition = reactive({
// });
// const onSearchSubmit = () => {
//   console.log("submit!");
// };
// const resetSearchForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

// 表格部分
const dataList = ref([]);
const total = ref(0);
const modalState = ref("ADD");
const formRef = ref<FormInstance>();
const state = reactive({
  modelForm: {
    id: null,
    classroomLocation: "",
    classroomName: "",
    maxSize: 0,
    used: 0,
  },
});
const { modelForm } = toRefs(state);

// 表单信息验证
const formRules = reactive<FormRules>({
  classroomLocation: [
    {
      required: true,
      message: "请输入教室所在位置，如7栋7楼",
      trigger: "blur",
    },
    {
      min: 4,
      max: 10,
      message: "请输入教室所在位置，如7栋7楼",
      trigger: "blur",
    },
  ],
  classroomName: [
    { required: true, message: "请输入教室名称,如6教", trigger: "blur" },
    { min: 2, max: 10, message: "请输入教室名称,如6教", trigger: "blur" },
  ],
  maxSize: [{ required: true, message: "请输入大容纳人数", trigger: "blur" }],
  used: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
});

// 列表请求
async function getInitData() {
  try {
    const res = await getClassroomApi({
      page: currentPage.value,
      size: pageSize.value,
    });
    console.log("列表请求：", res);
    if (res.data.code == "200") {
      dataList.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (err) {
    console.log("请求失败：", err);
    ElMessage.error("请求失败，请稍后重试!");
  }
}

onMounted(() => {
  getInitData();
});
// 刷新数据
const refreshData = () => {
  modalState.value = "ADD";
  currentPage.value = 1;
  getInitData();
};

// 模态框
const dialogVisible = ref(false);
const onCloseDialog = () => {
  // console.log("关闭模态框");
  formRef.value!.resetFields();
};
// 打开新增模态框
const onOpenAddDialog = () => {
  dialogVisible.value = true;
  modalState.value = "ADD";
  title.value = "新增教室";
};

// 提交数据
const submitModalForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (!valid) return console.log("error submit!", fields);

    console.log("submit - " + modalState.value, modelForm);

    try {
      const res =
        modalState.value == "ADD"
          ? await addClassroomApi(modelForm.value)
          : await editClassroomApi(modelForm.value);

      console.log("结果：", res);

      if (res.data.code == "200") {
        dialogVisible.value = false;

        ElMessage({
          type: "success",
          message: res.data.msg,
        });
      } else {
        ElMessage.error(res.data.code.msg);
      }
    } catch (err) {
      console.log("请求失败：", err);
      ElMessage.error("请求失败，请稍后重试!");
    }
  });
};
// 删除班级数据
const onDelHandler = async (row: any) => {
  ElMessageBox.confirm("确认删除该条信息吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        console.log(row);
        const res = await delClassroomApi(row.id);
        console.log("删除班级数据结果：", res);

        if (res.data.code == "200") {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getInitData();
        } else {
          ElMessage.error(res.data.msg);
        }
      } catch (err) {
        console.log("删除班级请求失败：", err);
        ElMessage.error("请求失败，请稍后重试!");
      }
    })
    .catch(() => {
      console.log("取消删除");
    });
};

// 查看班级信息
const onViewHandler = (row: any) => {
  console.log(row);
  modalState.value = "VIEW";
  title.value = "查看班级";
  getClassroomByIdApi(row.id)
    .then((res) => {
      console.log("查看班级信息：", res.data);
      modelForm.value = res.data.data;
    })
    .catch((err) => {
      console.log("查看班级信息：", err);
    });
  dialogVisible.value = true;
};

// 编辑班级信息
const onEditHandler = (row: any) => {
  console.log(row);
  modalState.value = "EDIT";
  title.value = "编辑班级";
  getClassroomByIdApi(row.id)
    .then((res) => {
      modelForm.value = res.data.data;
    })
    .catch((err) => {
      console.log("获取班级信息失败：", err);
    });
  dialogVisible.value = true;
};

// 表单重置
const resetModalForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<template>
  <main>
    <div class="page-header">
      <div class="page-title">
        <p>教室管理</p>
      </div>
    </div>
    <div class="page-body">
      <!-- 搜索 -->
      <!-- <div class="search">
        <el-form
          ref="searchFormRef"
          :inline="true"
          :model="searchCondition"
          class="demo-form-inline"
        >
          <el-form-item label="部门编号">
            <el-input
              v-model="searchCondition.class"
              style="width: 100px"
              size="small"
            />
          </el-form-item>
          <el-form-item label="方向">
            <el-select
              v-model="searchCondition.subject"
              class="m-2"
              size="small"
              style="width: 100px"
            >
              <el-option
                v-for="item in subjects"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="onSearchSubmit"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              size="small"
              type="primary"
              @click="resetSearchForm(searchFormRef)"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div> -->

      <!-- 批量操作 -->
      <div class="batch-processing">
        <div>
          <el-button type="primary" link @click="onOpenAddDialog"
            >新增教室</el-button
          >
        </div>
        <el-icon class="class_refresh" :size="22" @click="refreshData"
          ><Refresh
        /></el-icon>
      </div>

      <!-- 列表 -->
      <div class="student-list">
        <el-table :data="dataList" stripe border style="width: 100%">
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column label="序号" width="55">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="name" label="方向编号" width="90" /> -->
          <el-table-column prop="classroomName" label="教室名字" width="90" />
          <el-table-column
            prop="classroomLocation"
            label="教室位置"
            width="90"
          />
          <el-table-column prop="maxSize" label="最大容纳量" width="100" />
          <el-table-column prop="used" label="当前状态" width="100">
            <template #default="scope">
              {{ scope.row.used ? "在用" : "空置" }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button link size="small" @click="onViewHandler(scope.row)"
                >查看</el-button
              >
              <el-button
                link
                size="small"
                type="warning"
                @click="onEditHandler(scope.row)"
                >编辑</el-button
              >
              <el-button
                link
                size="small"
                type="danger"
                @click="onDelHandler(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <el-pagination
        small
        background
        layout="prev, pager, next"
        :total="total"
        class="mt-4"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      />

      <!-- 教室模态框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="title"
        width="60%"
        @close="onCloseDialog"
      >
        <el-form
          ref="formRef"
          :model="modelForm"
          :rules="formRules"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="教室id">
            <el-input :value="modelForm.id" disabled />
          </el-form-item>
          <el-form-item label="教室地址" prop="classroomLocation">
            <el-input
              v-model="modelForm.classroomLocation"
              placeholder="请输入"
              :disabled="modalState == 'VIEW'"
            />
          </el-form-item>
          <el-form-item label="教室编号" prop="classroomName">
            <el-input
              v-model="modelForm.classroomName"
              placeholder="请输入"
              :disabled="modalState == 'VIEW'"
            />
          </el-form-item>
          <el-form-item label="容纳量" prop="maxSize">
            <el-input
              v-model="modelForm.maxSize"
              placeholder="请输入"
              :disabled="modalState == 'VIEW'"
            />
          </el-form-item>
          <el-form-item label="教室状态" prop="used">
            <el-select
              v-model="modelForm.used"
              placeholder="请选择"
              :disabled="modalState == 'VIEW'"
            >
              <el-option label="空置" :value="0"></el-option>
              <el-option label="在用" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer" v-if="modalState != 'VIEW'">
            <el-button type="primary" @click="submitModalForm(formRef)"
              >提交</el-button
            >
            <el-button @click="resetModalForm(formRef)">重置</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </main>
</template>

<style lang="scss">
@import "@/assets/scss/global.scss";
.student-list {
  padding: 20px 0;
}
.batch-processing {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.class_refresh {
  &:hover {
    color: $color-theme;
  }
}
</style>
